#ifndef CAMERAVIDEOBUFFER_H
#define CAMERAVIDEOBUFFER_H

#include <QAbstractVideoSurface>
#include <QDebug>
#include <QVideoFrame>
#include <QQueue>
#include <QMutex>
#include <QCamera>

class CameraVideoBuffer : public QAbstractVideoSurface
{
    Q_OBJECT
    Q_PROPERTY(bool running READ running WRITE setRunning)
    Q_PROPERTY(int  camid READ camid WRITE setCamID)

signals:
    void newFrame(const QVideoFrame&);
public:
    explicit CameraVideoBuffer(QObject *parent=NULL);
    QList<QVideoFrame::PixelFormat> supportedPixelFormats(QAbstractVideoBuffer::HandleType handleType) const
    {
        qDebug()<<"supportedPixelFormats:"<<handleType;
        QList<QVideoFrame::PixelFormat> list;
        list.append(QVideoFrame::Format_RGB24);
        list.append(QVideoFrame::Format_ARGB32);
        return list;
    }
    virtual bool present(const QVideoFrame &frame)
    {
        emit newFrame(frame);
        Push(frame);
        return true;
    }

    void Push(QVideoFrame frame);
    bool top(QVideoFrame& first);
    void Pop();

    int camid() const{
        return mCamId;
    }
    void setCamID(int idx){
        if(idx==mCamId)
            return;
        mCamId=idx;
        StopCamera();
        StartCamera();
    }


    void setRunning(bool r){
        if(mRunning==r)
            return;

        mRunning=r;
        if(r)
            StartCamera();
        else
            StopCamera();
    }
    bool running() const{
        return mRunning;
    }

private:

    void StartCamera();
    void StopCamera();


    QCamera           *mpCamera;
    int               mCamId;
    bool              mRunning;

    QVector<QVideoFrame> mFrameBuffer;
    QMutex mLock;
};
#endif // CAMERAVIDEOBUFFER_H
